from rest_framework.views import APIView
from rest_framework.generics import GenericAPIView
from rest_framework.response import Response
from meiduo06.libs.captcha.captcha import captcha
from django_redis import get_redis_connection
from django.http.response import HttpResponse
from . import constants
from . import serializers


class ImageCodeView(APIView):
    """图形验证码视图"""

    def get(self, request, image_code_id):

        # 生成image_code
        text, image = captcha.generate_captcha()

        # 存储到redis
        redis_conn = get_redis_connection("verify_codes")
        redis_conn.setex("image_%s" % image_code_id, constants.IMAGE_CODE_EXPIRES, text)

        # 将图片返回
        return HttpResponse(image, content_type="images/jpg")


# GET /sms_codes/(?P<mobile>1[3-9]\d{9})/?image_code_id=xxx&text=xxx
class SMSCodeView(GenericAPIView):
    """手机验证码视图"""
    serializer_class = serializers.SMSCodeSerializer
    def get(self, request, mobile):
        serializer = self.get_serializer(data=request.query_params)
        serializer.is_valid(raise_exception=True)
        return Response({"message":"OK，发送成功"})